package com.heima.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.heima.model.article.pojos.ArticleDoc;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.search.service.SearchService;
import org.apache.commons.lang3.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;


@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private RestHighLevelClient client;


    @Override
    public ResponseResult search(UserSearchDto dto) {
        if(dto==null){
            return ResponseResult.errorResult(501,"参数失效");
        }
        SearchRequest request=new SearchRequest("app_info_article");
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        if(StringUtils.isNoneBlank(dto.getSearchWords())) {
            boolQuery.must(QueryBuilders.matchQuery("all", dto.getSearchWords()));
        }else{
            boolQuery.must(QueryBuilders.matchAllQuery());
        }
        if(dto.getMinBehotTime()!=null){
            boolQuery.filter(QueryBuilders.rangeQuery("publishTime").lt(dto.getMinBehotTime()));
        }
        request.source().highlighter(new HighlightBuilder().field("title").preTags("<font style='color:red;font-size:inherit;'>").postTags("</font>").requireFieldMatch(false));
        request.source().query(boolQuery);
        request.source().from(dto.getPageNum()).size(dto.getPageSize());
        try {
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            SearchHits hits = response.getHits();
            long total = hits.getTotalHits().value;
            SearchHit[] hitsHits = hits.getHits();
            List<ArticleDoc> list = new ArrayList<>();
            if(hitsHits!=null &&hitsHits.length>0){
                for (SearchHit hitsHit : hitsHits) {
                    String source = hitsHit.getSourceAsString();
                    ArticleDoc articleDoc = JSON.parseObject(source, ArticleDoc.class);
                    Map<String, HighlightField> highlightFields = hitsHit.getHighlightFields();
                    if(highlightFields!=null &&highlightFields.size()>0){
                        HighlightField field = highlightFields.get("title");
                        if (field != null) {
                            String name = field.getFragments()[0].string();
                            articleDoc.setH_title(name);
                        }
                    }
                    list.add(articleDoc);
                }
            }
            return ResponseResult.okResult(list);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }




    @Override
    public ResponseResult load(UserSearchDto dto) {
        //TODO
        return null;
    }
}
